import { Component, Vue, PropSync } from 'vue-property-decorator';
import moment from 'moment';
import { Modal, Form, Input, Row, Col, Radio, DatePicker, Upload } from 'ant-design-vue';

@Component({
  components: {
    'a-modal': Modal,
    'a-row': Row,
    'a-col': Col,
    'a-form': Form,
    'a-input': Input,
    'a-radio': Radio,
    'a-upload': Upload,
    'a-date-picker': DatePicker,
    'a-radio-group': Radio.Group,
    'a-form-item': Form.Item
  }
})
export default class ChangePassword extends Vue {
  @PropSync('_visible', {
    default: false
  })
  visible!: boolean;
  /** 用户头像 */
  avatar: string = '/assets/images/desktop/note.png';
  /** 用户信息 */
  userInfo: any = {};
  /** 是否能点击确定 */
  canClick: boolean = false;
  /** 表单 */
  form: any;

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'changePUserinfo' });
  }

  created() {
    const currentHumanInfo = JSON.parse(sessionStorage.getItem('currentHumanInfo') as any);
    const sysConfigMap = JSON.parse(sessionStorage.getItem('sysConfigMap') as any);
    if (sysConfigMap.WEB_PROJECT_CHOOSE === "2") {
      this.avatar = "/assets/images/desktop/avatar.jpg";
    }
    this.getAvatar(currentHumanInfo.humanId);
    this.getUserInfo();
    this.canClick = true;
  }

  async getAvatar(humanId: number) {
    const data = await Vue.prototype.$axios.get('/media/api/avatar?id=' + humanId);
    if (data !== null && data !== '' && typeof data === 'string') {
      this.avatar = 'data:image/jpeg;base64,' + data;
    }
  }

  async uploadAvatar(event: any) {
    const file: File = event.file;
    const formData: FormData = new FormData();
    formData.append('file', file, file.name);
    const data = await Vue.prototype.$axios.post('/media/api/uploadavatar?id=0', formData);
    this.avatar = 'data:image/jpeg;base64,' + data.src;
    this.$emit("setAvatar", data.src);
  }

  async getUserInfo() {
    const data = await Vue.prototype.$axios.get('/system/api/humaninfo/profile');
    this.userInfo = data;
    this.form.setFieldsValue({
      humanName: data.humanName,
      identityNum: data.identityNum,
      gender: data.gender,
      birthday: moment(data.birthday, 'YYYY-MM-DD'),
      telephone: data.telephone,
      unitName: data.unitName,
      lawCardNum: data.lawCardNum
    });
  }

  onOk() {
    if (!this.canClick) return;
    this.form.validateFields().then(async (data: any) => {
      const params = {
        ...this.userInfo,
        ...data
      };
      await Vue.prototype.$axios.post('/system/api/humaninfo/updateprofile', params);
      this.$message.success('保存成功');
      this.visible = false;
    }).catch(() => { });
  }
}